let visitModule = (function () {

  let $tableBox = $(".tableBox"),
    $tbody = $tableBox.find('tbody'),
    $visitTime = $(".visitTime"),
    $visitText = $(".visitText"),
    $submit = $(".submit");

  let params = null,
    customerId = 0;

  async function bindHTML() {
    let result = await axios.get(`/visit/list?customerId=${customerId}`)
    console.log(result)
    if (result.code !== 0) {
      // return
    }
    if (!result.data) {
      $tbody.html('当前零条回访记录，请添加！');
      return;
    }
    let str = ``;
    result.data.forEach(item => {
      let {
        id,
        customerId,
        customerName,
        visitText,
        visitTime
      } = item;
      str += `
        <tr>
          <td class="w5">${id}</td>
          <td class="w15">${visitTime}</td>
          <td class="w70 wrap">${visitText}</td>
          <td class="w10" id="${id}">
            <a href="javascript:;">删除</a>
          </td>
        </tr> 
      `;
    })
    $tbody.html(str);
  }

  // customerId=xxx&visitText=xxx&visitTime=xxx
  function handleEvent() {
    // 添加回访记录
    $submit.click(async function () {
      let result = await axios.post(`/visit/add`, {
        customerId,
        visitText: $visitText.val().trim(),
        visitTime: $visitTime.val()
      })
      if (result.code !== 0) {
        alert("添加失败，请重试！");
        return;
      }
      alert("本次回访记录添加成功");
      bindHTML();
    })
    // 删除回访记录
    $tbody.click(async ev => {
      let target = ev.target,
        $target = $(target),
        TAG = target.tagName;
      if (TAG === "A") {
        let id = $target.parent().attr("id");
        let visitId = parseInt(id);
        let result = await axios.get("/visit/delete", { params: { visitId } });
        if (result.code !== 0) {
          alert('删除失败，请重试！')
          return;
        }
        alert(`id为${visitId}删除成功！`);
        bindHTML();
      }
    })
  }

  return {
    init() {
      // 获取传递过来的id值
      params = window.location.href.queryURLParams();
      customerId = params.customerId;

      bindHTML();
      handleEvent();
    }
  }
})();
visitModule.init();